﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;

namespace mvcDemo.Controllers
{
    public class LogTool
    {
        //日志路径
        private static string path = HttpContext.Current.Request.PhysicalApplicationPath + @"logs";
        //日志级别及保留天数
        private static IDictionary dict = ConfigurationManager.GetSection("LogSetting") as IDictionary;
        private static int level = int.Parse(dict["level"].ToString());
        private static int keepdates = int.Parse(dict["keepdates"].ToString());

        private static object locker = new object();

        /// <summary>
        /// 写入调试日志
        /// </summary>
        /// <param name="className">日志类别</param>
        /// <param name="content">日志内容</param>
        public static void Debug(string className,string[] content)
        {
            if (level >= 3)
            {
                WriteLog("DEBUG", className, content);
            }
        }

        /// <summary>
        /// 写入运行时日志
        /// </summary>
        /// <param name="className">日志类别</param>
        /// <param name="content">日志内容</param>
        public static void Info(string className, string content)
        {
            if (level >= 2)
            {
                WriteLog("INFO", className, new string[] { content });
            }
        }

        /// <summary>
        /// 写入错误日志
        /// </summary>
        /// <param name="className">日志类别</param>
        /// <param name="content">日志内容</param>
        public static void Error(string className, string[] content)
        {
            if (level >= 1)
            {
                WriteLog("ERROR", className, content);
            }
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="type">日志类型</param>
        /// <param name="className">日志类别</param>
        /// <param name="content">日志内容</param>
        protected static void WriteLog(string type, string className, string[] content)
        {
            try
            {
                lock (locker)
                {
                    //按日志类型分开文件夹
                    string typePath = path + "\\" + type;
                    if (!Directory.Exists(typePath))
                    {
                        Directory.CreateDirectory(typePath);
                    }
                                                            
                    //每天一个日志文件
                    DateTime now = DateTime.Now;
                    string fileFullPath = typePath + "\\" + now.ToString("yyyy-MM-dd") + ".log";

                    //创建或打开日志文件，向日志文件末尾追加记录
                    StreamWriter sw = System.IO.File.AppendText(fileFullPath);

                    //向日志文件写入内容
                    string write_content = HttpContext.Current.Request.RawUrl + " " + now.ToString("yyyy-MM-dd HH:mm:ss") + " " + className + ": ";
                    for(int i = 0; i < content.Length; i++)
                    {
                        write_content += content[i].Length == 0 ? "" : (content[i] + "\r\n");
                    }
                    sw.WriteLine(write_content);
                    sw.Flush();
                    //关闭文件
                    sw.Close();
                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 删除过期日志
        /// </summary>
        public static void DeleteLog()
        {
            try
            {
                DateTime now = DateTime.Now;
                string[] subPath = Directory.GetDirectories(path);
                foreach (string subpath in subPath)
                {
                    string[] files = Directory.GetFiles(subpath);
                    foreach (string file in files)
                    {
                        FileInfo fi = new FileInfo(file);
                        TimeSpan ts = now - fi.CreationTime;
                        if (ts.Days > keepdates)
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
        }
    }
}